<?php

if (!defined('IN_XLP')) {
    exit('Access Denied!');
}

/**
 * Description of newsAction
 *
 * @author xlp
 */
class nearbyAction extends commonAction {

    function __construct() {
        parent::__construct();
        $this->nearbyTaglist = F("nearby_taglist");
    }

    public function index() {
        parent::_checkLogin();
        $p = $this->_getid('p');
        $tid = $this->_getid('tag', 0);
        $act = $this->_get('act', 'index');
        $where = array(
            'aid' => admin::$adminInfo['aid']
        );
        if ($tid) {
            $where['tag_id'] = $tid;
        }
        $rs = M('nearby_thread')->where($where)->page($p)->order('px desc,id desc')->findAll();
        $total = M('nearby_thread')->getTotal();
        $result = array();
        if ($rs) {
            foreach ($rs as $key => $val) {
                $result[$key]['id'] = $val['id'];
                if ($val['type'] == 2) { //多条图文时
                    $result[$key]['type'] = 'more';
                    $result[$key]['header'] = $val;
                    $rsItem = M('nearby_thread')->field('id,title,description,picurl,infotime')->where(array('fid' => $val['id']))->order('id asc')->limit(0, 7)->findAll();
                    if ($rsItem) {
                        $result[$key]['items'] = $rsItem;
                    }
                } else {
                    $result[$key]['type'] = 'one';
                    $result[$key]['header'] = $val;
                }
            }
        }
        //        z($result);
        $this->assign(array(
            'rs' => $result,
            'p' => $p,
            'total' => $total,
            'taglist' => $this->nearbyTaglist
        ));
        $this->assign(array(
            'tid' => $tid,
            'act' => $act
        ));
        $this->display();
    }

    public function detail() {
        $id = $this->_getid('id');
        if (!$id) {
            showError('参数丢失');
        }
        $rs = M('nearby_thread')->where(array(
                    'id' => $id
                ))->find();
        if (!$rs) {
            showError('文章不存在或已删除');
        }
        jumpTo(U('weixin/nearby/detail', array(
            'fid' => $id
        )));
        if ($rs && isHave($rs['url']) && !isHave($rs['content'])) {
            $url = strExists($rs['url'], 'content/') ? str_replace('content/', 'weixin/', $rs['url']) : $rs['url'];
            jumpTo($url);
            exit;
        }
        $this->assign('rs', $rs);
        $this->display();
    }

    //编辑身边事
    public function edit() {
        parent::_checkLogin();
        $id = $this->_getid('id');
        if (!$id) {
            showError('参数丢失');
        }
        $rs = M('nearby_thread')->where(array(
                    'aid' => admin::$adminInfo['aid'],
                    'id' => $id
                ))->find();
        if ($rs) {
            $objData = array();
            $objData['id'] = $rs['id'];
            $objData['tid'] = $rs['tid'];
            if ($rs['type'] == 2) { //多条图文时
                $objData['fid'] = $rs['id'];
                $objData['type'] = 'more';
                $objData['header'] = $rs;
                $rsItem = M('nearby_thread')->field('id,title,author,is_putin,picurl,content,url')->where(array(
                            'fid' => $rs['id']
                        ))->order('infotime desc')->limit(0, 7)->findAll();
                if ($rsItem) {
                    $objData['items'] = $rsItem;
                }
                //                array_unshift($objData['items'], $rs);
            } else {
                $objData['fid'] = 0;
                $objData['type'] = 'one';
                $objData['header'] = $rs;
            }
        }
        //        z($objData);
        $this->assign(array(
            'rs' => $objData,
            'taglist' => $this->nearbyTaglist
        ));
        if ($objData['type'] == 'one') {
            $this->display('edit_one');
        } else {
            $this->display('edit_more');
        }
    }

    //添加身边事
    public function add() {
        parent::_checkLogin();
        $tid = $this->_getid('tid', 0);
        $this->assign(array(
            'tid' => $tid,
            'taglist' => $this->nearbyTaglist
        ));
        $this->display('add_one');
    }

    //上传图片
    public function postpic() {
        if (!isHave($_POST['s_auth']) || !isHave($_POST['s_saltkey'])) {
            echo json_encode(array(
                'result' => 'error',
                'msg' => '验证失败'
            ));
            exit;
        } else {
            admin::getLoginUser(null, array(
                'auth' => $_POST['s_auth'],
                'saltkey' => $_POST['s_saltkey']
            ));
        }
        parent::_checkLogin();
        load('upload');
        $myUpload = new Myupload();
        $upload = $myUpload->upload('news/u' . admin::$adminInfo['aid']);
        $upload = parent::_sendImageToYunServer($upload); //同步图片到云存储
        if ($upload) {
            $upload = $upload[0];
            if (!$upload) {
                echo json_encode(array('result' => 'error', 'msg' => $myUpload->getErrorMsg()));
            } else {
                echo json_encode(array(
                    'fileUrl' => getImgUrl($upload['savepath']),
                    'fileName' => $upload['realname'],
                    'savePath' => $upload['savepath']
                ));
            }
        }
    }

    //正常上传
    public function upload() {
        if (parent::_checkLogin(true)) {
            load('upload');
            $myUpload = new Myupload();
            $upload = $myUpload->upload('news/u' . admin::$adminInfo['aid']);
            $upload = parent::_sendImageToYunServer($upload); //同步图片到云存储
            if ($upload) {
                $upload = $upload[0];
                if (!$upload) {
                    echo json_encode(array('url' => '', 'fileType' => '', 'original' => '', 'state' => $myUpload->getErrorMsg()));
                } else {
                    echo json_encode(array(
                        'url' => getImgUrl($upload['savepath']),
                        'fileType' => $upload['type'],
                        'original' => $upload['realname'],
                        'state' => 'SUCCESS'
                    ));
                }
            }
        } else {
            echo json_encode(array(
                'url' => '',
                'fileType' => '',
                'original' => '',
                'state' => '上传失败'
            ));
            exit;
        }
    }

    //新建身边事图文信息
    public function post() {
        parent::_checkLogin();
        T('content/validate');
        $action = $this->_post('act', 'add');
        $tid = $this->_postid('tid', 0);
        $px = $this->_postid('px', 0);
        $data = $this->_post('data', '', 'trim');
        if (!$data || !is_array($data)) {
            $this->JsonReturn('内容不能为空');
        }
        $mainNewsData = array();
        if (isset($data[0])) {
            $mainNewsData = $data[0];
            unset($data[0]);
        }
        //主新闻处理
        //============
        $objData = array();
        $objData['tid'] = $tid;
        $objData['fid'] = 0;
        $objData['aid'] = admin::$adminInfo['aid'];
        $objData['village_id'] = admin::$adminInfo['village_id'];
        $objData['title'] = $mainNewsData['title'];
        $objData['type'] = $action == 'add' ? 1 : 2;
        $objData['tag_id'] = $mainNewsData['tagid'];
        $objData['description'] = isHave($mainNewsData['summary']) ? $mainNewsData['summary'] : ''; //摘要
        $objData['content'] = parent::_clearFilter($mainNewsData['content']); //正文
        $objData['picurl'] = $mainNewsData['coverurl'];
        /*
          $pattern                = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/";
          preg_match_all($pattern, $objData['content'], $match);
          if(isHave($match[1])){
          $objData['picurl']   = str_ireplace("http://img.51jhome.com/", "", $match[1][0]);
          $imagelist = array_slice($match[1], 0, 4);
          }
          $objData['picurl'] =isHave($objData['picurl'])?$objData['picurl'] :"";

          $picurl    = "";
          if(isHave($imagelist)){
          foreach ($imagelist as $ik => $iv) {
          $iv = str_ireplace("http://img.51jhome.com/", "", $iv);
          $picurl .= $iv . ",";
          }
          }
          $objData['picurls']  = substr($picurl, 0, -1); //图片
         */
        $objData['url'] = parent::_clearFilter($mainNewsData['source_url']); //来源URL
        $objData['status'] = 1;
        $objData['px'] = $px;
        $objData['infotime'] = TIME;
        //内容规则检查
        $validate = array(
            array(
                'title',
                'range_length',
                '标题长度为2-80个字符',
                2,
                80
            ),
            array(
                'content',
                'max_length',
                '内容长度为必须小于20000个字符',
                20000
            )
        );
        if (!validate::check($validate, $objData)) {
            $this->JsonReturn(validate::getError());
        }
        //        print_r($_POST);
        //        z($objData);
        $mainNewsId = M('nearby_thread')->insert($objData);
        //============
        if ($action == 'add') { //添加单条图文
            if ($mainNewsId) {
                $this->JsonReturn('ok', null, 1);
            } else {
                $this->JsonReturn('添加失败');
            }
        } else {
            if (!$mainNewsId) {
                $this->JsonReturn('正文插入失败');
            }
            $itemData = array();
            if ($data && $mainNewsId) {
                $validate = array(
                    array(
                        'title',
                        'range_length',
                        '标题长度为2-80个字符',
                        2,
                        80
                    ),
                    //array('picurl', 'required', '必须上传图片'),
                    array(
                        'content',
                        'max_length',
                        '内容长度为必须小于20000个字符',
                        20000
                    )
                );
                foreach ($data as $val) {
                    $objData = array(
                        'tid' => $tid,
                        'fid' => $mainNewsId,
                        'aid' => admin::$adminInfo['aid'],
                        'village_id' => admin::$adminInfo['village_id'],
                        'title' => $val['title'],
                        'type' => 2,
                        'author' => $val['author'],
                        'is_putin' => $val['isCover'] ? 1 : 0,
                        'description' => '',
                        'picurl' => $val['coverurl'],
                        'content' => parent::_clearFilter($val['content']),
                        'url' => parent::_clearFilter($val['source_url']),
                        'status' => 1,
                        'px' => 0,
                        'infotime' => TIME
                    );
                    //内容规则检查
                    if (!validate::check($validate, $objData)) {
                        $this->JsonReturn(validate::getError());
                    }
                    $itemData[] = $objData;
                }
            }
            //            print_r($_POST);
            //            z($itemData);
            if ($itemData) {
                M('nearby_thread')->insertAll($itemData);
                $this->JsonReturn('ok', null, 1);
            } else {
                $this->JsonReturn('error');
            }
        }
    }

    //保存身边事图文信息修改
    public function save() {
        //        z($_POST);
        parent::_checkLogin();
        T('content/validate');
        $action = $this->_post('act', 'edit');
        $tid = $this->_postid('tid', 0);
        $data = $this->_post('data', '', 'trim');
        $id = $this->_postid('id', 0);
        $px = $this->_postid('px', 0);
        if (!$id) {
            $this->JsonReturn('参数丢失');
        }
        if (!$data || !is_array($data)) {
            $this->JsonReturn('内容不能为空');
        }
        $rs = M('nearby_thread')->where(array(
                    'aid' => admin::$adminInfo['aid'],
                    'id' => $id
                ))->find();
        if (!$rs) {
            $this->JsonReturn('内容不存在');
        }
        $mainNewsData = array();
        if (isset($data[0])) {
            $mainNewsData = $data[0];
            unset($data[0]);
        }
        //主新闻处理
        //============
        $objData = array();
        $objData['tid'] = $tid;
        $objData['title'] = $mainNewsData['title'];
        $objData['description'] = isHave($mainNewsData['summary']) ? $mainNewsData['summary'] : ''; //摘要
        $objData['content'] = parent::_clearFilter($mainNewsData['content']); //正文
        $objData['url'] = parent::_clearFilter($mainNewsData['source_url']); //来源URL
        $objData['px'] = $px;
        $objData['picurl'] = $mainNewsData['coverurl'];
        /*
          $pattern                = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/";
          preg_match_all($pattern, $objData['content'], $match);
          if(isHave($match[1])){
          $objData['picurl']   = str_ireplace("http://img.51jhome.com/", "", $match[1][0]);
          $imagelist = array_slice($match[1], 0, 4);
          }

          $objData['picurl'] =isHave($objData['picurl'])?$objData['picurl'] :"";
          $picurl    = "";
          if(isHave($imagelist)){
          foreach ($imagelist as $ik => $iv) {
          $iv = str_ireplace("http://img.51jhome.com/", "", $iv);
          $picurl .= $iv . ",";
          }
          }
          $objData['picurls'] = substr($picurl, 0, -1); //图片
         */
        //内容规则检查
        $validate = array(
            array(
                'title',
                'range_length',
                '标题长度为2-80个字符',
                2,
                80
            ),
            //array('picurl', 'required', '必须上传图片'),
            array(
                'content',
                'max_length',
                '内容长度为必须小于20000个字符',
                20000
            )
        );
        if (!validate::check($validate, $objData)) {
            $this->JsonReturn(validate::getError());
        }
        M('nearby_thread')->update($objData, array(
            'id' => $id
        ));
        //============
        if ($action == 'edit') { //编辑单条图文
            $this->JsonReturn('ok', null, 1);
        } else {
            $itemData = array();
            if ($data) {
                $validate = array(
                    array(
                        'title',
                        'range_length',
                        '标题长度为2-80个字符',
                        2,
                        80
                    ),
                    array(
                        'content',
                        'max_length',
                        '内容长度为必须小于20000个字符',
                        20000
                    )
                );
                foreach ($data as $val) {
                    $objData = array(
                        'tid' => $tid,
                        'title' => $val['title'],
                        'author' => $val['author'],
                        'is_putin' => $val['isCover'] ? 1 : 0,
                        'description' => '',
                        'picurl' => $val['coverurl'],
                        'content' => parent::_clearFilter($val['content']),
                        'url' => parent::_clearFilter($val['source_url'])
                    );
                    //内容规则检查
                    if (!validate::check($validate, $objData)) {
                        $this->JsonReturn(validate::getError());
                    }
                    if ($val['rid']) {
                        M('nearby_thread')->update($objData, array(
                            'id' => $val['rid']
                        ));
                    } else {
                        $objData['tid'] = $tid;
                        $objData['fid'] = $id;
                        $objData['aid'] = admin::$adminInfo['aid'];
                        $objData['village_id'] = admin::$adminInfo['village_id'];
                        $objData['type'] = 2;
                        $objData['status'] = 1;
                        $objData['infotime'] = TIME;
                        $objData['px'] = 0;
                        $itemData[] = $objData;
                    }
                }
            }

            if ($itemData) {
                $this->JsonReturn('ok', null, 1);
            }
            $this->JsonReturn('ok', null, 1);
        }
    }

    public function delete() {
        /*
         * 注意这里删除的时候还要查找是否有自定义回复的内容
         */
        parent::_checkLogin();
        $id = $this->_postid('id');
        if (!$id) {
            showError('参数丢失');
        }
        M('nearby_thread')->delete("id IN (" . $id . ") AND aid=" . admin::$adminInfo['aid']);
        $this->JsonReturn('ok', null, 1);
    }

    public function tags_list() {
        $p = $this->_getid('p', '1');
        $pager = 20;
        $taglist = M("nearby_tags")->order("sort desc")->limit(($p - 1) * $pager, $pager)->findAll();
        $totle = M("nearby_tags")->getTotal();
        $this->assign(array(
            'rs' => $taglist,
            'p' => $p,
            'total' => $totle,
            'pager' => $pager
        ));
        $this->display();
    }

    public function tags_add() {
        $this->display();
    }

    public function tags_post() {
        $data['tag_title'] = $this->_post("tag_title");
        $data['sort'] = $this->_post("sort");
        $data['city_id'] = admin::$adminInfo['city_id'];
        $data['aid'] = admin::$adminInfo['aid'];
        $rs = M("nearby_tags")->insert($data);
        if ($rs) {
            $this->set_tags();
            $this->JsonReturn('ok', null, 1);
        }
    }

    public function tags_edit() {
        $tid = $this->_getid("id");
        $rs = M("nearby_tags")->where(array(
                    "tag_id" => $tid
                ))->find();
        $this->assign(array(
            'rs' => $rs
        ));
        $this->display();
    }

    public function tags_save() {
        $where['tag_id'] = $this->_postid("id");
        $data['tag_title'] = $this->_post("tag_title");
        $data['sort'] = $this->_post("sort");
        $rs = M("nearby_tags")->update($data, $where);
        if ($rs) {
            $this->set_tags();
            $this->JsonReturn('ok', null, 1);
        }
    }

    public function tags_delete() {
        $id = $this->_postid("id");
        $totle = M("nearby_thread")->where(array(
                    "tag_id" => $id
                ))->count();
        if (!$totle) {
            $rs = M('nearby_tags')->delete("tag_id = " . $id . " AND aid=" . admin::$adminInfo['aid']);
            if ($rs) {
                $this->set_tags();
                $this->JsonReturn('ok', null, 1);
            }
        } else {
            $this->JsonReturn('不能删除，该标签下还有对应的身边事');
        }
    }

    public function tags_status() {
        $where['tag_id'] = $this->_postid("id");
        $data['status'] = $this->_postid("act");
        $rs = M("nearby_tags")->update($data, $where);
        if ($rs) {
            $this->set_tags();
            $this->JsonReturn('ok', null, 1);
        }
    }

    public function set_tags() {
        $rs = M("nearby_tags")->order("sort desc")->findAll();
        foreach ($rs as $rk => $rv) {
            $rss[$rv['tag_id']] = $rv;
        }
        F("nearby_taglist", $rss);
    }

    public function cover() {
        $this->assign(array(
            'coverurl' => F("nearby_cover")
        ));
        $this->display();
    }

    public function cover_post() {
        $cover = $this->_post('coverurl');
        if ($cover) {
            F("nearby_cover", $cover);
            $this->JsonReturn('ok', null, 1);
        }
    }

}
